package cn.u313.lymusic.activity

import android.os.Bundle
import android.os.Environment
import android.view.Menu
import android.view.MenuItem
import android.widget.SearchView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.Composable
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import cn.u313.lymusic.R
import cn.u313.lymusic.adapter.SearchItemAdapter
import cn.u313.lymusic.databinding.ActivitySearchBinding
import cn.u313.lymusic.model.SearchModel
import cn.u313.lymusic.ui.dialog.DownloadFromDialog
import cn.u313.lymusic.utils.click
import cn.u313.lymusic.utils.hide
import cn.u313.lymusic.utils.show
import cn.u313.lymusic.viewmodel.MusicDownloadViewModel
import com.arialyy.aria.core.Aria

class SearchActivity : BaseAppActivity<ActivitySearchBinding>(),SearchItemAdapter.Listener {

    private val musicVm by lazy {
        ViewModelProvider(this)[MusicDownloadViewModel::class.java]
    }
    private val mData = mutableListOf<SearchModel.Data>()
    private val searchAdapter by lazy {
        SearchItemAdapter(this,mData)
    }
    override fun getViewBinding(): ActivitySearchBinding {
        return ActivitySearchBinding.inflate(layoutInflater)
    }

    override fun initData() {

    }
    private var n = 1
    private var searchName = ""
    override fun iniClick() {
        vb.tvMore.hide()
        vb.tvMore.click {
            showLoading()
            musicVm.search(searchName,++n)
        }
    }

    override fun observe() {
        musicVm.searchModel.observe(this) {
            hideLoading()
            vb.tvMore.show()
            mData.clear()
            it?.data?.let { it1 -> mData.addAll(it1) }
            searchAdapter.notifyDataSetChanged()
        }
        musicVm.searchMoreModel.observe(this) {
            hideLoading()
            val index = mData.size
            it?.data?.let { it1 -> mData.addAll(it1) }
            searchAdapter.notifyDataSetChanged()
            vb.rvSearch.scrollToPosition(index)
        }
        musicVm.downloadUrl.observe(this) {
            runOnUiThread {
                Toast.makeText(this, "开始下载", Toast.LENGTH_SHORT).show()
            }
            if (it != null) {
                Aria.download(this)
                    .load(it)
                    .ignoreCheckPermissions()
                    .setFilePath(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                            .getPath() + String.format(
                            "/%s.%s",
                            musicVm.musicInfo.value?.fileName(),
                            if (it.contains("flac")) "flac" else "mp3"
                        )
                    )
                    .create()
            };
        }
    }

    override fun initView() {
        vb.rvSearch.layoutManager = LinearLayoutManager(this)
        vb.rvSearch.adapter = searchAdapter
        searchAdapter.listener = this
    }

    fun search(text: String) {
        searchName = text
        n = 1
        window.currentFocus?.clearFocus()
        showLoading()
        musicVm.search(text)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu (this adds items to the action bar if it is present).
        menuInflater.inflate(R.menu.menu_search, menu)

        val searchItem = menu.findItem(R.id.action_search)
        val searchView = searchItem.actionView as SearchView

        // 设置搜索框的提示文字
        searchView.queryHint = "输入音乐名称"

        // 设置SearchView的事件监听器
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                // 用户提交查询时的回调
                // 可以在这里处理搜索请求
                if (query != null) {
                    search(query)
                }
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                // 用户输入时的回调，可以动态更新UI
                // newText就是当前输入的文本
                return true
            }
        })

        // 设置SearchView关闭时的监听
        searchView.setOnCloseListener {
            // 处理SearchView关闭事件
            false
        }

        // 确保搜索框首次展开时获得焦点
        searchView.isIconified = false // 展开 SearchView
        searchView.requestFocus() // 获取焦点
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_search -> {
                // 处理搜索按钮点击事件
                true
            }

            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun clickItem(data: SearchModel.Data) {
        DownloadFromDialog(data,musicVm).show(this.supportFragmentManager,"1")
    }

}